package com.meitianhui.convenitenbuy.module.wallet.ui.activity;

import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.zxing.WriterException;
import com.meitianhui.convenitenbuy.App;
import com.meitianhui.convenitenbuy.Constants;
import com.meitianhui.convenitenbuy.R;
import com.meitianhui.convenitenbuy.base.BaseToolbarActivity;
import com.meitianhui.convenitenbuy.config.InfoProvider;
import com.meitianhui.convenitenbuy.main.model.bean.EventBean;
import com.meitianhui.convenitenbuy.module.wallet.contract.WalletPaymentShowContract;
import com.meitianhui.convenitenbuy.module.wallet.di.DaggerWalletComponent;
import com.meitianhui.convenitenbuy.module.wallet.di.WalletModule;
import com.meitianhui.convenitenbuy.module.wallet.model.CodeFlowBean;
import com.meitianhui.convenitenbuy.module.wallet.presenter.WalletPaymentShowPresenter;
import com.meitianhui.convenitenbuy.push.model.PushBean;
import com.meitianhui.convenitenbuy.util.LogUtils;
import com.meitianhui.convenitenbuy.util.RxBus;
import com.meitianhui.convenitenbuy.util.RxTimerUtils;
import com.meitianhui.convenitenbuy.util.SystemUtils;
import com.meitianhui.convenitenbuy.util.TipUtils;
import com.meitianhui.convenitenbuy.util.ZXingUtils;

import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class WalletPaymentShowActivity extends BaseToolbarActivity implements WalletPaymentShowContract.View {
    TextView mTvAsset;
    ImageView mIvQRCode;
    RxTimerUtils mRx;
    String stringExtra;
    @Inject
    WalletPaymentShowPresenter mPresenter;

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        DaggerWalletComponent.builder().appComponent(App.getInstance().getAppComponent()).walletModule(new WalletModule(this)).build().inject(this);
        setTbTitle(getString(R.string.wallet_payment_code));
        setTbMenu(getString(R.string.wallet_payment_show_clear));
        mRx = new RxTimerUtils();
        initId();
        initInfo();
        isEnable(false);
        initTimer();
    }

    @Override
    protected int setView() {
        return R.layout.activity_wallet_payment_show;
    }

    private void initId() {
        mTvAsset = getViewById(R.id.tv_wallet_payment_show);
        mIvQRCode = getViewById(R.id.iv_wallet_payment_show);
        stringExtra = getIntent().getStringExtra(Constants.ARGUMENT);
        mTvAsset.setText(stringExtra);
        registerPush();
    }


    /**
     * 获取用户付款码
     */
    private void initInfo() {
        mPresenter.getPaymentCode();
    }

    @Override
    protected void clickMenu() {
        finish();
    }

    /**
     * 显示二维码
     *
     * @param bean
     */
    private void showQRCode(CodeFlowBean bean) {

        try {
            mIvQRCode.setImageBitmap(ZXingUtils.createQRCode(createCode(bean), 250));
            Animation a = AnimationUtils.loadAnimation(this, R.anim.zoom_in);
            mIvQRCode.setAnimation(a);
        } catch (WriterException e) {
            LogUtils.e("create QR code fail.");
        }
    }

    private String createCode(CodeFlowBean bean) {
        Map<String, String> map = new HashMap<String, String>();
        String type = "P";
        map.put("type", type);
        map.put("security_code", bean.getSecurity_code());
        map.put("flow_no", bean.getFlow_no());
        map.put("member_id", InfoProvider.getUserToken(App.getInstance()).getMember_id());
        map.put("member_type_key", "consumer");
        map.put("amount", stringExtra);
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        return new Gson().toJson(map);

    }

    private void initTimer() {
        RxTimerUtils.IRxNext next = new RxTimerUtils.IRxNext() {

            @Override
            public void doNext(long number) {
                initInfo();
            }
        };
        mRx.interval(60000, next);

    }

    @Override
    protected void onResume() {
        super.onResume();
        initInfo();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRx.cancel();
    }


    @Override
    protected void onRefreshData() {

    }


    @Override
    public void showError(String msg) {

    }

    @Override
    public void getPaymentCodeBack(CodeFlowBean result) {
        showQRCode(result);
    }

    private void registerPush() {
        Disposable disposable = RxBus.get().toFlowable(PushBean.class).subscribe(new Consumer<PushBean>() {
            @Override
            public void accept(PushBean bean) throws Exception {
                if (bean != null) {
                    if (bean.getType().equals(Constants.PUSH_TYPE_SCAN_PAY_SUCCESS)) {
                        SystemUtils.vibrate(WalletPaymentShowActivity.this, new long[]{100, 400}, -1);
                        TipUtils.showToast(WalletPaymentShowActivity.this, getString(R.string.wallet_change_recharge_success), 1);
                        RxBus.get().post(new EventBean(Constants.EVENT_TYPE_REFRESH));
                        finish();
                    }
                }
            }
        });

        Disposable disposable1 = RxBus.get().toFlowable(EventBean.class).subscribe(new Consumer<EventBean>() {
            @Override
            public void accept(EventBean bean) throws Exception {
                if (bean != null) {
                    if (bean.type == Constants.EVENT_TYPE_REFRESH) {
                        initInfo();
                    }
                }
            }
        });
        mCompositeDisposable.add(disposable);
        mCompositeDisposable.add(disposable1);
    }
}
